package com.ouc.pampas;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConfigServiceImpl implements ConfigService {
	@Autowired
	private ConfigManager configManager;

	public List<AppWithConfigInfo> listAllAppWithConfigInfo() {
		List<App> appList = this.configManager.listAllApp();
		List<AppWithConfigInfo> result = Lists.newArrayList();
		for (App app : appList) {
			AppWithConfigInfo appWithConfigInfo = new AppWithConfigInfo();
			appWithConfigInfo.setApp(app);
			FrontConfig frontConfig = this.configManager.getFrontConfig(app.getKey());
			if (frontConfig != null) {
				appWithConfigInfo.setFrontConfig(
						new AppWithConfigInfo.ConfigInfo(frontConfig.getSign(), frontConfig.getLoadedAt()));
			}
			BackConfig backConfig = this.configManager.getBackConfig(app.getKey());
			if (backConfig != null) {
				appWithConfigInfo.setBackConfig(
						new AppWithConfigInfo.ConfigInfo(backConfig.getSign(), backConfig.getLoadedAt()));
			}
			result.add(appWithConfigInfo);
		}
		return result;
	}

	public App getApp(String appKey) {
		List<App> apps = this.configManager.listAllApp();
		for (App app : apps) {
			if (Objects.equal(app.getKey(), appKey)) {
				return app;
			}
		}
		return null;
	}

	public FrontConfig getFrontConfig(String appKey) {
		return this.configManager.getFrontConfig(appKey);
	}

	public BackConfig getBackConfig(String appKey) {
		return this.configManager.getBackConfig(appKey);
	}
}
